package com.dev.security.interceptor;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpUtil;
import com.dev.security.entity.Log;
import com.dev.security.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import sun.plugin.extension.ExtensionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.CompletionStage;

/** 日志拦截器
 * #Author:槐序二四
 * #Time：2020/4/15 16:19
 * #Motto:人间荒唐市侩 不如山中作怪🌙.
 */

public class LogInterceptor implements HandlerInterceptor {

    @Autowired
    private LogService logService;

    /**
     * 方法执行前 如果是false，请求就会返回，其余方法不再执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long start = System.currentTimeMillis();
        request.setAttribute("startTime",start);

        return true;
    }

    /**
     * 方法执行后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 渲染 完成执行后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        long start = (long) request.getAttribute("startTime");
        long end = System.currentTimeMillis();
        long cost = end - start;

        Log log = new Log();
        log.setUserId(10);
        log.setUserName("超级用户");
        log.setCost(cost);
        log.setIpAddress(HttpUtil.getClientIP(request));
        log.setRequestPath(request.getRequestURI());
        log.setIsError(0);

        if (ex != null){
            log.setIsError(1);
            log.setError(ExceptionUtil.stacktraceToString(ex));
        }

        logService.save(log);
    }
}
